package com.example.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.pojo.Result;
import com.example.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter(filterName = "TokenFilter", urlPatterns = "/emps/*")
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {

        Filter.super.destroy();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //1.获取请求url
        String url = req.getRequestURL().toString();
        log.info("请求的url: {}", url);
        //2.判断是否包含login, 包含login直接放行
        if(url.contains("login")){
            log.info("拦截的url: {}", url);
            chain.doFilter(request, response);
            return;
        }
        //3.获取请求头中的token
        String token = req.getHeader("Authorization");
        log.info("token: {}", token);
        //4.判断token是否为空，如果为空表示未登录，返回未登录信息(json)
        if(token==null || token.isEmpty()){
            Result error = Result.error("token不能为空");
            System.out.println(error);
            String json =JSONObject.toJSONString(error);
            resp.getWriter().write(json);
            return;
        }
        //5.解析token，如果解析失败表示登录信息已经过期，返回未登录信息(json)
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            Result error = Result.error("登录信息过期");
            String json =JSONObject.toJSONString(error);
            resp.getWriter().write(json);
            return;
        }
        //6.放行
        log.info("验证成功，放行");
        chain.doFilter(request, response);
    }
}
